package org.ehe.erp.service.quality.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.service.OssService;
import org.ehe.common.oss.entity.UploadResult;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.erp.domain.quality.ErpQualityAttachment;
import org.ehe.erp.domain.quality.bo.ErpQualityAttachmentBo;
import org.ehe.erp.domain.quality.vo.ErpQualityAttachmentVo;
import org.ehe.erp.mapper.quality.ErpQualityAttachmentMapper;
import org.ehe.erp.service.quality.ErpQualityAttachmentService;
import org.ehe.system.domain.vo.SysOssVo;
import org.ehe.system.service.ISysOssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 质检附件ServiceImpl
 * @author :zhangnn
 * @className :ErpQualityAttachmentServiceImpl
 * @description: TODO
 * @date 2025-09-10 16:33:05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpQualityAttachmentServiceImpl extends ServiceImpl<ErpQualityAttachmentMapper,ErpQualityAttachment> implements ErpQualityAttachmentService {

    private final ISysOssService ossService;
    @Override
    public UploadResult upload(MultipartFile file) {
        SysOssVo upload = ossService.upload(file);
        SysOssVo sysOssVo = ossService.getById(upload.getOssId());
        return UploadResult.builder()
            .filename(sysOssVo.getOriginalName())
            .eTag(sysOssVo.getFileSuffix())
            .url(sysOssVo.getUrl())
            .build();
    }

    /**
     * 根据反馈ID查询
     */
    public List<ErpQualityAttachmentVo> listByFeedbackId(Long feedbackId) {
        return lambdaQuery().eq(ErpQualityAttachment::getFeedbackId, feedbackId)
            .orderByDesc(ErpQualityAttachment::getUploadTime)
            .list()
            .stream()
            .map(a -> BeanUtil.copyProperties(a, ErpQualityAttachmentVo.class))
            .toList();
    }

    /**
     * 批量保存附件（事务内调用）
     */
    public void saveBatch(List<ErpQualityAttachmentBo> list) {
        if (CollUtil.isEmpty(list)) return;
        List<ErpQualityAttachment> entities = BeanUtil.copyToList(list, ErpQualityAttachment.class);
        entities.forEach(a -> {
            if (a.getUploadTime() == null) a.setUploadTime(LocalDateTime.now());
            if (a.getUploadPerson() == null) a.setUploadPerson(LoginHelper.getUsername());
        });
        saveBatch(entities);
    }

    @Override
    public int deleteWithValidByIds(List<Long> ids) {
        ids.forEach(id->{
            this.baseMapper.deleteById(id);
        });
        return 0;
    }
}
